package com.sendi.system.action;

import java.io.IOException;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.BeanUtils;

import com.sendi.system.entity.Dctdata;
import com.sendi.system.entity.User;

public class DctDataAction extends SysAction {
	
	private Integer id;
	private String dcttypenote;
	private String dcttypeen;
	private String selecttype;
	private String selectsql;
	private String displayname;
	private String valuename;
	private String displayvalue;
	private String valuetext;
	private String otherfieldname;
	private String otherfieldvalue;
 
	  
	public DctDataAction()
	{
		super();
		data_session_name="DctDataActionListData";
	}
	
	
	public void DctDataInit()
	{
		List datas=null;
		
		if(getSession().getAttribute(data_session_name)!=null)
		{
			datas=(List)getSession().getAttribute(data_session_name);
			System.out.println("use session size"+datas.size());
		}
		else
		{
			addDctDataToSesson();
			datas=(List)getSession().getAttribute(data_session_name);
		}
	//	this.sortObjectList(datas);
			writeJSONArray(datas);
		 
	}
	
	public void addDctDataToSesson()
	{
		List datas=null;
		String hql="from  Dctdata ";
	 	datas=serviceSupportImp.findByHQL(hql);
	 	getSession().setAttribute(data_session_name,datas);
	 	System.out.println("data size:"+datas.size());
	}
	
	public void queryDctData()
	{
		   try
		   {
			     Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
			 	StringBuffer hql=new StringBuffer("from Dctdata where 1=1 ");
				if(dcttypenote!=null&&dcttypenote.trim().length()>0)
				{
					hql.append(" and  dcttypenote like :dcttypenote ");
				}
			 	
				   Query query= session.createQuery(hql.toString());
				   if(dcttypenote!=null&&dcttypenote.trim().length()>0)
					{
					  query.setParameter("dcttypenote", "%"+dcttypenote+"%");
					}
					 
					    List datas=query.list();
					    System.out.println("query size"+datas.size());
				     	getSession().setAttribute(data_session_name,datas);	
				     	writeResponseText("{success:true,msg:'success',datasize:"+datas.size()+"}");
		   			}
		   catch (Exception e) {
			   writeResponseText("{success:false,msg:'failure'}");
				 
		}
		    
		
	}
	public void queryDctDataAndreturn()
	{
		   try
		   {
			     Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
			 	StringBuffer hql=new StringBuffer("from Dctdata where 1=1 ");
				if(dcttypenote!=null&&dcttypenote.trim().length()>0)
				{
					hql.append(" and  dcttypenote like :dcttypenote ");
				}
			 	
				   Query query= session.createQuery(hql.toString());
				   if(dcttypenote!=null&&dcttypenote.trim().length()>0)
					{
					  query.setParameter("dcttypenote", "%"+dcttypenote+"%");
					}
					 
					    List datas=query.list();
					    String datastr=JSONArray.fromObject(datas).toString();
				     	System.out.println(datastr);
				     	writeResponseText(datastr);
		   			}
		   catch (Exception e) {
			   writeResponseText("{success:false,msg:'failure'}");
				 
		}
		    
		
	}

	public void queryDctDatawidthen()
	{
		 
		   try
		   {
			     Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
			 	StringBuffer hql=new StringBuffer("from Dctdata where 1=1 ");
				if(dcttypeen!=null&&dcttypeen.trim().length()>0)
				{
					hql.append(" and  dcttypeen =:dcttypeen ");
				}
			 	
				   Query query= session.createQuery(hql.toString());
				   if(dcttypeen!=null&&dcttypeen.trim().length()>0)
					{
					  query.setParameter("dcttypeen", dcttypeen);
					}
					 
					    List datas=query.list();
					    if(datas.size()>0)
					    {
					    	Dctdata dt=(Dctdata)datas.get(0);
					    	if(dt.getSelecttype().equals("sql"))//如果是使用sql
					    	{
					    		datas =new ArrayList<Dctdata>();
					    		String sql=dt.getSelectsql();
					    		String sqlt="";
					    		if(sql.indexOf("#")!=-1&&sql.indexOf("%")!=-1)
					    		{
					    			//将sql 语句中的参数，替换为session中的值 ,参数写法为#参数 名称%,参数必须为数字，字母与下线线如：#user_id%,以#开始,%结尾,中间不能存在#,%
					    		     Pattern pp = Pattern.compile("\\#[a-z|_|0-9|A-Z]+\\%"); 
					    			  Matcher m  =pp.matcher(sql); 
					    		  	 HttpSession s=this.getSession();
					    		       while(m.find())
					    		      {
					    		    	 
					    		    	  String str=m.group();
					    		    	  sqlt= sql.replaceAll(str,(String)s.getAttribute(str.replace("#","").replace("%","")));
					    		       }
					    		       sql=sqlt;
					     		}
					     		ResultSet rs=excuteQuery(sql);
					    		if(rs!=null)   //将sql 查询得到的数据构造成Dctdata返回
					    		{
					    			 String displayfield=dt.getDisplayname();
					    			 String valutfield=dt.getValuename();
					    			 
					    			while(rs.next())
					    			{
					    				Dctdata newdt=new Dctdata();
					    				String dispalyvalue=rs.getString(displayfield);
					    				String valutext=rs.getString(valutfield);
					    				String othervalue="";
					    				 
					    				newdt.setDcttypeen(dt.getDcttypeen());
					    				newdt.setDcttypenote(dt.getDcttypenote());
					    				newdt.setDisplayname(displayfield);
					    				newdt.setValuename(valutfield);
					    				newdt.setDisplayvalue(dispalyvalue);
					    				newdt.setValuetext(valutext);
					    				newdt.setOtherfieldname("");
					    				newdt.setOtherfieldvalue(othervalue);
					    				datas.add(newdt);
					    			}
					    		}
					     	}
					    }
					   
					    String datastr=JSONArray.fromObject(datas).toString();
				     	System.out.println(datastr);
				     	writeResponseText(datastr);
		   			}
		   catch (Exception e) {
			   writeResponseText("{success:false,msg:'failure'}");
				 
		}
		    
		
	}
	
	
	 public void addDctData()
	 {
	 	 Dctdata dctdata=new Dctdata(dcttypenote, dcttypeen, selecttype, selectsql,displayname,valuename, displayvalue,  valuetext, otherfieldname,otherfieldvalue);
	 		try {
				serviceSupportImp.save(dctdata);
				getSession().removeAttribute(data_session_name);
				addDctDataToSesson();
				writeResponseText("{success:true,msg:'success'}");
		 	} catch (Exception e) {
				writeResponseText("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
			  e.printStackTrace();
			}
	 }

	 
	 public void excutModifyQueryDctData()
		{
			System.out.println("excutModifyQuery...."+id);
			String hql="from Dctdata where 1=1 and id="+this.id; 
			
			List datas=serviceSupportImp.findByHQL(hql);
		 
		 	System.out.println("data size:"+datas.size());
		 	Dctdata dctdata=(Dctdata)datas.get(0);
			try {
				System.out.println("{success:true,datas:"+JSONObject.fromObject(dctdata).toString()+"}");
				writeResponseText("{success:true,datas:"+JSONObject.fromObject(dctdata).toString()+"}");
		   	} catch (Exception e) {
				try {
					getResponse().getWriter().write("{success:false,msg:'faild',errors:{"+e.getMessage()+"}}");
				} catch (IOException e1) {
				 
					e1.printStackTrace();
				}
				e.printStackTrace();
			}
			
		}
		public void excuteModifyDctData()
		{
			System.out.println("excuteModify...."+id);
			String hql="from Dctdata where 1=1 and id="+this.id; 
			
			List datas=serviceSupportImp.findByHQL(hql);
		 
		 	System.out.println("data size:"+datas.size());
		 	Dctdata dctdata=(Dctdata)datas.get(0);
		 
		 	 Dctdata dctdata2=new Dctdata(dcttypenote, dcttypeen, selecttype, selectsql,displayname,valuename, displayvalue,  valuetext, otherfieldname,otherfieldvalue);
			String ignoreProperties[]={"id","selecttype"};
		 	BeanUtils.copyProperties(dctdata2, dctdata,ignoreProperties);
		 	serviceSupportImp.update(dctdata);
		 	getSession().removeAttribute(data_session_name);
			 addDctDataToSesson();
			writeResponseText("{success:true,msg:'success'}"); 
		}
		
		public void excuteDeleteDctData()
		{
		  String hql="delete Dctdata where id in ("+deleterecord+")";
		  Session session=serviceSupportImp.getDao().getSessionFactory().openSession();
		  session.beginTransaction();
		  session.createQuery(hql).executeUpdate();
		  session.getTransaction().commit();
		  addDctDataToSesson();
		  writeResponseText("{success:true,msg:'success'}"); 
		}
		
		
	public Integer getId() {
		return id;
	}


	public void setId(Integer id) {
		this.id = id;
	}


	public String getDcttypenote() {
		return dcttypenote;
	}


	public void setDcttypenote(String dcttypenote) {
		this.dcttypenote = dcttypenote;
	}


	public String getDcttypeen() {
		return dcttypeen;
	}


	public void setDcttypeen(String dcttypeen) {
		this.dcttypeen = dcttypeen;
	}


	public String getSelecttype() {
		return selecttype;
	}


	public void setSelecttype(String selecttype) {
		this.selecttype = selecttype;
	}


	public String getSelectsql() {
		return selectsql;
	}


	public void setSelectsql(String selectsql) {
		this.selectsql = selectsql;
	}


	public String getDisplayname() {
		return displayname;
	}


	public void setDisplayname(String displayname) {
		this.displayname = displayname;
	}


	public String getValuename() {
		return valuename;
	}


	public void setValuename(String valuename) {
		this.valuename = valuename;
	}


	public String getDisplayvalue() {
		return displayvalue;
	}


	public void setDisplayvalue(String displayvalue) {
		this.displayvalue = displayvalue;
	}


	public String getValuetext() {
		return valuetext;
	}


	public void setValuetext(String valuetext) {
		this.valuetext = valuetext;
	}


	public String getOtherfieldname() {
		return otherfieldname;
	}


	public void setOtherfieldname(String otherfieldname) {
		this.otherfieldname = otherfieldname;
	}


	public String getOtherfieldvalue() {
		return otherfieldvalue;
	}


	public void setOtherfieldvalue(String otherfieldvalue) {
		this.otherfieldvalue = otherfieldvalue;
	}


 
	

}
